package jp.wug.util;

import com.google.inject.TypeLiteral;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class TypeLiteralUtil {
    private TypeLiteralUtil() {
    }

    public static boolean isAssignable(TypeLiteral from, TypeLiteral to) {
        Type fromType = from.getType();
        if (fromType instanceof Class) {
            return isAssignable((Class<?>) fromType, to);
        } else {
            return from.equals(to);
        }
    }

    public static boolean isAssignable(Class<?> fromClass, TypeLiteral to) {
        Type toType = to.getType();
        if (toType instanceof Class) {
            Class<?> toClass = (Class) toType;
            return toClass.isAssignableFrom(fromClass);
        } else if (toType instanceof ParameterizedType) {
            /*unchecked assignment*/
            ParameterizedType toParameterizedType = (ParameterizedType) toType;
            Type toRawType = toParameterizedType.getRawType();
            if (toRawType instanceof Class) {
                Class<?> toClass = (Class) toRawType;
                return toClass.isAssignableFrom(fromClass);
            }
        }
        return false;
    }
}
